@echo off
chcp 65001 >nul
cd /d "%~dp0"

:: 简化版启动脚本 - 避免递归调用
echo ========================================
echo    星痕共鸣 - 快速启动
echo ========================================
echo.

echo [INFO] 正在启动浏览器端和桌面端...
echo [%time%] 快速启动开始 > quick_start.log

:: 检查主项目
if not exist "server.js" (
    echo [ERROR] 主项目文件未找到！
    echo [%time%] ERROR: server.js not found >> quick_start.log
    echo [INFO] 当前目录: %CD%
    echo.
    echo 按任意键退出...
    pause >nul
    exit /b 1
)

:: 检查依赖
if not exist "node_modules" (
    echo [WARNING] 正在安装主项目依赖...
    echo [%time%] Installing main dependencies >> quick_start.log
    call install.bat
)

:: 检查悬浮窗
if not exist "floating_overlay\node_modules" (
    echo [WARNING] 正在安装悬浮窗依赖...
    echo [%time%] Installing overlay dependencies >> quick_start.log
    cd floating_overlay
    call install_overlay.bat
    cd ..
)

:: 停止现有服务
echo [INFO] 清理现有进程...
echo [%time%] Cleaning existing processes >> quick_start.log
taskkill /f /im node.exe >nul 2>&1
taskkill /f /im electron.exe >nul 2>&1
timeout /t 2 >nul

:: 启动主服务器
echo [START] 启动主服务器...
echo [%time%] Starting main server >> quick_start.log
start /b cmd /c "node server_wrapper.js > server_quick.log 2>&1"

:: 等待服务器启动
echo [WAIT] 等待服务器就绪...
set /a counter=0
:wait_loop
timeout /t 1 >nul
set /a counter+=1
netstat -an | find ":8989" >nul 2>&1
if %errorLevel% neq 0 (
    if %counter% lss 20 (
        goto wait_loop
    ) else (
        echo [ERROR] 服务器启动失败！
        echo [%time%] ERROR: Server startup failed >> quick_start.log
        echo 按任意键退出...
        pause >nul
        exit /b 1
    )
)

echo [SUCCESS] 服务器启动成功！
echo [%time%] Server started successfully >> quick_start.log

:: 启动浏览器
echo [START] 打开浏览器...
echo [%time%] Opening browser >> quick_start.log
start http://localhost:8989

:: 等待浏览器加载
timeout /t 3 >nul

:: 启动悬浮窗
echo [START] 启动悬浮窗...
echo [%time%] Starting overlay >> quick_start.log
cd floating_overlay
start /b cmd /c "npx electron . --no-sandbox > overlay_quick.log 2>&1"
cd ..

echo.
echo ========================================
echo           启动完成！
echo ========================================
echo.
echo 🌐 浏览器: http://localhost:8989
echo 🎯 悬浮窗: 已启动 (可能需要几秒显示)
echo.
echo [INFO] 关闭此窗口将停止所有服务
echo [INFO] 按 Ctrl+C 停止服务
echo.

:: 监控服务
:monitor
echo [%time%] 服务运行中... (按Ctrl+C停止)
timeout /t 30 >nul
goto monitor
